package cn.anecansaitin.whimsy.common.network;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.common.capabilities.battle.IBattleMode;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import software.bernie.geckolib.util.ClientUtils;

public record BattleModeAnimPack(int entityId, String controllerName, String animName) implements CustomPacketPayload {
    public static final ResourceLocation ID = Whimsy.resource("battle_mode_anim_pack");

    public BattleModeAnimPack(FriendlyByteBuf buf) {
        this(buf.readVarInt(), buf.readUtf(), buf.readUtf());
    }

    @Override
    public void write(FriendlyByteBuf buffer) {
        buffer.writeVarInt(entityId);
        buffer.writeUtf(this.controllerName == null ? "" : this.controllerName);
        buffer.writeUtf(this.animName);
    }

    @Override
    public ResourceLocation id() {
        return ID;
    }

    public static void clientHandler(BattleModeAnimPack data, PlayPayloadContext context) {
        context.workHandler().submitAsync(() -> {
            Entity entity = ClientUtils.getLevel().getEntity(data.entityId);

            if (!(entity instanceof LivingEntity livingEntity)) {
                return;
            }

            IBattleMode battleMode = livingEntity.getCapability(IBattleMode.BATTLE_MODE);

            if (battleMode == null) {
                return;
            }

            battleMode.getController().triggerAnim(livingEntity, data.controllerName, data.animName);
        });
    }
}
